<script lang="ts">
	import { onMount, onDestroy, type Component } from 'svelte';
	import LoadingComponent from '$lib/components/ExceptionPage/LoadingComponent.svelte';
	import ErrorComponent from '$lib/components/ExceptionPage/ErrorComponent.svelte';
	import Portal from 'svelte-portal';
	import Icon from '$lib/components/Basic/Icon/Icon.svelte';
	import { browser } from '$app/environment';
	// ======================================
	// 关键修正1：补充 ModalBody 组件类型定义（解决类型不匹配）
	// ======================================
	type ModalBodyProps = {
		modalBody?: any;
		onModalBodyLoaded: () => void; // 匹配 ModalBody 暴露的回调 props
	};
	// 定义动态导入的模块类型（Svelte 组件默认导出为 default）
	type ModalBodyModule = {
		default: Component<ModalBodyProps>;
	};

	// ======================================
	// 1. Props定义（完全保留你的代码，仅修正 onModalLoaded 语法笔误）
	// ======================================
	const {
		children,
		visible = false,
		title = '',
		initWidth = '500px',
		initHeight = '300px',
		isLoading = false,
		top = '100px',
		left = '0px',
		modalTitle,
		modalFoot,
		onUpdateVisible = () => {},
		onModalLoaded = () => {} // 修正语法：补充 = 符号（原代码少写 =）
	} = $props<{
		children?: any;
		visible: boolean;
		title: string;
		initWidth: string;
		initHeight: string;
		isLoading?: boolean;
		top?: string;
		left?: string;
		modalTitle?: () => void;
		modalFoot?: () => void;
		onUpdateVisible: (visible: boolean) => void; // 修正语法：去掉多余 =（TS 类型定义不允许赋值）
		onModalLoaded: () => void; // 修正语法：去掉多余 () 并补全类型定义
	}>();

	// ======================================
	// 2. 响应式变量（保持你的代码不变）
	// ======================================
	let renderLoading = $state(true);
	let modalRef: HTMLElement | null = $state(null);
	let isTransition = $state(false);
	let isDragging = $state(false);
	let isResizing = false;
	let startPos = { x: 0, y: 0 };
	let startOffSet = { x: 0, y: 0 };
	let startSize = { x: parseFloat(initWidth), y: parseFloat(initHeight) };
	let windowStyle: {
		width: any;
		height: any;
		top: any;
		left: any;
		transform: string;
	} = $state({
		width: initWidth,
		height: initHeight,
		top: top,
		left: left,
		transform: 'translate(0px, 0px)'
	});
	let isMaximized = $state(false);
	let originWindowStyle = $state({
		width: initWidth,
		height: initHeight,
		top: top,
		left: left,
		transform: 'translate(0px, 0px)'
	});
	const minWidth = 500;
	const minHeight = 300;

	// ======================================
	// 3. 懒加载ModalBody（保持你的代码不变）
	// ======================================
	const modalBodyPromise: Promise<ModalBodyModule> = import('./ModalBody.svelte');

	// ======================================
	// 4. 核心逻辑（保持你的代码不变）
	// ======================================
	function startDrag(event: MouseEvent) {
		event.preventDefault();
		event.stopPropagation();
		if (!isMaximized) {
			isDragging = true;
			startPos.x = event.clientX;
			startPos.y = event.clientY;
			document.addEventListener('mousemove', doDrag);
			document.addEventListener('mouseup', stopDrag);
		}
	}

	function doDrag(event: MouseEvent) {
		if (isDragging && modalRef) {
			const deltaX = event.clientX - startPos.x + startOffSet.x;
			const deltaY = event.clientY - startPos.y + startOffSet.y;
			windowStyle.transform = `translate(${deltaX}px, ${deltaY}px)`;
		}
	}

	function stopDrag() {
		if (isDragging) {
			isDragging = false;
			const matches = /translate\((.+?)px, (.+?)px\)/.exec(windowStyle.transform);
			if (matches) {
				startOffSet.x = parseFloat(matches[1]);
				startOffSet.y = parseFloat(matches[2]);
			}
			document.removeEventListener('mousemove', doDrag);
			document.removeEventListener('mouseup', stopDrag);
		}
	}

	function startResize(event: MouseEvent) {
		event.preventDefault();
		event.stopPropagation();
		if (!isMaximized) {
			isResizing = true;
			startPos.x = event.clientX;
			startPos.y = event.clientY;
			document.addEventListener('mousemove', doResize);
			document.addEventListener('mouseup', stopResize);
		}
	}

	function doResize(event: MouseEvent) {
		if (isResizing) {
			const newWidth = Math.max(minWidth, event.clientX - startPos.x + startSize.x);
			const newHeight = Math.max(minHeight, event.clientY - startPos.y + startSize.y);
			windowStyle.width = `${newWidth}px`;
			windowStyle.height = `${newHeight}px`;
		}
	}

	function stopResize() {
		if (isResizing) {
			isResizing = false;
			startSize.x = parseFloat(windowStyle.width);
			startSize.y = parseFloat(windowStyle.height);
			document.removeEventListener('mousemove', doResize);
			document.removeEventListener('mouseup', stopResize);
		}
	}

	function maximize(event: MouseEvent) {
		event.preventDefault();
		event.stopPropagation();
		isTransition = true;
		if (isMaximized) {
			windowStyle = { ...originWindowStyle };
			isMaximized = false;
		} else {
			originWindowStyle = { ...windowStyle };
			windowStyle.width = '100vw';
			windowStyle.height = '100vh';
			windowStyle.top = '0px';
			windowStyle.left = '0px';
			windowStyle.transform = 'translate(0px, 0px)';
			isMaximized = true;
		}
		setTimeout(() => {
			isTransition = false;
		}, 200);
	}

	function close(event: MouseEvent | KeyboardEvent) {
		event.preventDefault();
		event.stopPropagation();
		startOffSet = { x: 0, y: 0 };
		windowStyle.transform = 'translate(0px, 0px)';
		onUpdateVisible(false);
	}

	function handleEscape(event: KeyboardEvent) {
		if (event.key === 'Escape' && visible) {
			close(event);
		}
	}

	function handleModalBodyLoaded() {
		renderLoading = false;
		onModalLoaded();
	}

	// ======================================
	// 5. 生命周期（保持你的代码不变）
	// ======================================
	onMount(() => {
		if (browser) {
			window.addEventListener('keydown', handleEscape);
		}
	});

	onDestroy(() => {
		if (browser) {
			document.removeEventListener('mousemove', doDrag);
			document.removeEventListener('mouseup', stopDrag);
			document.removeEventListener('mousemove', doResize);
			document.removeEventListener('mouseup', stopResize);
			window.removeEventListener('keydown', handleEscape);
		}
	});
</script>

{#if visible}
	<Portal target="body">
		<div class="modal-overlay elResetBody">
			<div
				class="modal-window {isMaximized ? 'modal-window-max' : ''}"
				class:window-transition={isTransition}
				bind:this={modalRef}
				style:width={windowStyle.width}
				style:height={windowStyle.height}
				style:top={windowStyle.top}
				style:left={windowStyle.left}
				style:transform={windowStyle.transform}
			>
				<div class="modal-header" onmousedown={startDrag} role="button" tabindex="0">
					{#if modalTitle && typeof modalTitle === 'function'}
						{@render modalTitle?.()}
					{:else}
						<div class="modalTitle">
							<div class="icon">
								<div class="filled"></div>
                                <div class="svg">in</div>
							</div>
							<span>{title}</span>
						</div>
					{/if}
					<div style="display: flex;">
						<button onclick={maximize} class="button-resize">
							<Icon src="office/maximize" size={12}></Icon>
						</button>
						<button onclick={close} class="button-close">
							<Icon src="symbol/close" size={18}></Icon>
						</button>
					</div>
				</div>

				<div class="modal-body">
					<div class="stack">
						{#await modalBodyPromise then { default: ModalBody }}
							<ModalBody onModalBodyLoaded={handleModalBodyLoaded}>
								{#snippet modalBody()}
									{@render children?.()}
								{/snippet}
							</ModalBody>
						{:catch}
							<ErrorComponent />
						{/await}

						{#if renderLoading || isLoading}
							<LoadingComponent />
						{/if}
					</div>
				</div>

				{@render modalFoot?.()}

				<div class="modal-resizer" onmousedown={startResize} role="button" tabindex="0"></div>
			</div>
		</div>
	</Portal>
{/if}

<style scoped lang="scss">
	/* 完全保留你的样式代码不变 */
	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: var(--color-overlay);
		display: flex;
		justify-content: center;
		align-items: top;
		z-index: 1000;
	}

	.modal-window {
		background-color: var(--color-page);
		border-radius: 12px;
		box-shadow: 0px 20px 60px 0px var(--color-shadow);
		min-width: 500px;
		min-height: 300px;
		position: relative;
		display: flex;
		flex-direction: column;
		overflow: hidden;

		.modal-body {
			display: flex;
			flex: 1;
			padding: 12px 12px 0 12px;
		}

		.modal-resizer {
			position: absolute;
			width: 10px;
			height: 10px;
			bottom: 0;
			right: 0;
			cursor: se-resize;
			border-bottom-right-radius: 16px;
		}
	}
	.window-transition {
		transition: all 0.2s ease;
	}

	.modal-window-max {
		border-radius: 0px;
	}

	.modal-header {
		height: 48px;
		padding: 0 12px;
		margin: 0 12px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		cursor: move;
		border-top-left-radius: 16px;
		border-top-right-radius: 16px;
		border-bottom: var(--border);

		.modalTitle {
			display: flex;
			align-items: center;
			.icon {
				position: relative;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 24px;
				height: 24px;
                background-color: var(--color-info-600);
                border-radius: 50%;
                cursor: pointer;
                transition: all 0.3s ease-in-out;
                overflow: hidden;                
                .svg {
                    font-size: 14px;
                    font-weight: bold;
                    color:#fff;
                    z-index:1;
                }
				.filled {           
					position: absolute;
					top: auto;
					bottom: 0;
					left: 0;
					width: 100%;
					height: 0;
					transition: all 0.3s ease-in-out;
					background-color: var(--color-primary-500);
				}
				&:hover {
                    color: var(--color-page);
                    .filled{
                        height: 100%;
                    }					
				}
			}
			span {
				margin-left: 12px;
				line-height: 16px;
				font-size: 14px;
				font-weight: bold;
			}
		}

		button {
			border: none;
			cursor: pointer;
			border-radius: 12px;
			display: flex;
			height: 24px;
			width: 24px;
			padding: 0;
			align-items: center;
			justify-content: center;
			transition:
				color 0.2s ease,
				background-color 0.2s ease;
		}
		.button-close {
			background-color: color-mix(in srgb, var(--color-error-500) 10%, transparent);
			color: var(--color-error-500);
			&:hover {
				background-color: var(--color-error-500);
				color: #fff;
			}
		}
		.button-resize {
			margin-right: 12px;
			background-color: var(--color-fill);
			&:hover {
				background-color: color-mix(in srgb, var(--color-info-700) 20%, transparent);
			}
		}
	}
	.stack {
		position: relative;
		width: 100%;
		height: 100%;
	}
</style>
